import { defineStore } from "pinia";
import { ElMessageBox } from "element-plus";

import { appendRoute, removeRoute } from "@/utils/menuAndRoute";
import { TMenu } from "@/router/menu";
import router from "@/router";
import appToken from "@/utils/appToken";
import { isUndefined } from "lodash-es";
import { useAppTabsStore } from "@/modules/package/appTabs";

interface IState {
  loading: boolean;

  menuIsCollapse: boolean;
  collapseAuto: boolean;

  menus: TMenu[];

  userInfo?: {
    id: number;
    account: string;
    avatar: string;
    nickname: string;
    mobile: string;
    role: 1 | 2;

    // avatar: string;
    // mobile: string | number;
    // // name: string;
    // nickname: string;

    // brand: string;
    // trademark: string; // 商标
    // merchant_type: 1 | 2 | 3; //  1 2 3
    // main_category: string;

    // audit_status: number; // 1 2 3
    // audit_time: string;
    // audit_reason: string;

    // province: string;
    // city: string;
    // district: string;
    // address: string;
  };

  // 任务栏状态
  taskIsShow: boolean;
  taksIsRunning: boolean;
}

const useApp = defineStore("app", {
  state: (): IState => {
    return {
      // 是否折叠
      menuIsCollapse: false,
      // 自动模式
      collapseAuto: true,

      // 菜单列表
      menus: [],

      // 页面顶部加载状态
      loading: false,
      //登录用户信息
      userInfo: undefined,

      // 任务拦
      taskIsShow: false,
      taksIsRunning: false,
    };
  },

  actions: {
    //
    changeCollapse(isCollapse?: boolean) {
      if (this.collapseAuto) {
        this.menuIsCollapse = isCollapse ?? !this.menuIsCollapse;
      } else if (!isUndefined(isCollapse)) {
        this.menuIsCollapse = isCollapse;
        this.collapseAuto = !isCollapse;
      }
    },

    // 添加路由，并渲染菜单
    appendRouter(menus: any[]) {
      appendRoute(menus);
      this.menus = menus;
    },

    // 退出登录
    async logout(force?: boolean) {
      if (!force) await ElMessageBox.confirm("确定退出登录吗？", "提示");

      this.userInfo = undefined;

      // 移除动态注册的所有路由
      removeRoute();
      useAppTabsStore().clear();
      appToken.cleartToken();
      this.menus.length = 0;
      router.replace("/login");

      // 保底方案
      setTimeout(() => {
        window.location.reload();
      }, 200);
    },

    // 切换加载状态
    toggleLoading(state?: boolean) {
      this.loading = state ?? !this.loading;
    },
  },

  persist: {
    paths: ["userInfo", "menuIsCollapse"],
  },
});

export default useApp;
